﻿var NotificationsPage = function(pageContainer) {

    NotificationsPage.superclass.constructor.call(this, pageContainer);

    var self = this;
    var currentIndex = 0;
    var initialSetSize = 30;
    var defaultSetSize = 20;
    var visibleElements = 0;
    var notificari = new Array();
    var isLoading = false;
    var isEditing = false;
    var lastUpdate = null;

    this.Actions = [
        {
            Text: 'Editare',
            Callback: function() { self.toggleEdit(); },
            CanExecute: function() { return true; }
        }
    ];

    var Elements = {
        notificationsList: pageContainer.find(".notificationsList"),
        pullUp: pageContainer.find(".pullUp"),
        nonotif: pageContainer.find('.nonotif'),
        deleteAllNotifications: pageContainer.find('.deleteAllNotifications')
    };

    var Templates = {
        notificationsTemplate: $(".notificationsTemplate"),
        notificationsTemplateCompiled: null
    };

    this.toggleEdit = function() {
        isEditing = !isEditing;

        if (isEditing) {
            if (app.LeftMenu && app.LeftMenu.instance && app.LeftMenu.instance.isVisible())
                app.LeftMenu.instance.hide();

            if (Elements.notificationsList.children().length)
                Elements.deleteAllNotifications.show();
        } else Elements.deleteAllNotifications.hide();

        if (app.MessagesFactory.isDialogVisible())
            app.MessagesFactory.hideDialog();

        Elements.notificationsList.find('.notification-container').each(function() {
            setEditable($(this), isEditing);
        });
    };

    this.refresh = function() {
        currentIndex = 0;
        isLoading = false;
        if (isEditing)
            self.toggleEdit();
        lastUpdate = null;
        Elements.notificationsList.empty();
        Elements.nonotif.hide();
        self.getPullUpData();
        notificari = new Array();
    };

    var setEditable = function(notif, isEditable) {
        if (isEditable) {
            notif.addClass('notification-container-delete-active');
            notif.find('.delete-notification').removeClass('notvisible');
        } else {
            notif.removeClass('notification-container-delete-active');
            notif.find('.delete-notification').addClass('notvisible');
        }
    };

    this.getPullDownData = function() {
        pageContainer.find(".loadMore").hide();
        self.refresh();
    };

    this.getPullUpData = function(callback) {
        if (isLoading)
            return;

        isLoading = true;

        var setSize = currentIndex == 0 ? initialSetSize : defaultSetSize;

        Elements.nonotif.hide();
        app.TMMService.TMM.GetNotifications(currentIndex, setSize, "", function(response) {
            $(document).trigger('hidePullDown');
            if (response.Exception) {
                if (app.CurrentPage.instance == self)
                    app.Phone.setModuleAction(ModuleActions.None);
                return;
            }

            addToList(response.FinalResult);

            if (currentIndex == 0 && response.FinalResult && response.FinalResult.length)
                lastUpdate = response.FinalResult[0].SENT_DATE;


            if (!visibleElements)
                calculateVisibleElements();

            if (!response.FinalResult.length || (currentIndex == 0 && response.FinalResult.length < visibleElements))
                pageContainer.find(".loadMore").hide();
            else if (!currentIndex)
                pageContainer.find(".loadMore").show();
            isLoading = false;

            currentIndex += response.FinalResult.length;

            if (currentIndex == 0) {
                Elements.nonotif.show();
                if (app.CurrentPage.instance == self)
                    app.Phone.setModuleAction(ModuleActions.None);
            } else {
                Elements.nonotif.hide();
                if (app.CurrentPage.instance == app.Pages.Notifications.instance)
                    app.Phone.setModuleAction(ModuleActions.Edit);
            }

            if (isEditing) {
                if (Elements.notificationsList.children().length)
                    Elements.deleteAllNotifications.show();
                else Elements.deleteAllNotifications.hide();
            }

            Elements.notificationsList.find('.delete-notification a').unbind('click').bind('click', function(e) {
                var msg_id = $(this).attr('data-tm-msg_id');
                if (msg_id) {
                    $(this).parents('.notification-container').remove();
                    readNotification(msg_id);
                }

                return Event.stopEvent(e);
            });
        });

        updateUnreadNotificationsCount();
    };

    var updateUnreadNotificationsCount = function() {
        app.TMMService.TMM.GetUnreadNotificationsCount(function(response) {
            if (!response.Exception) {
                Event.sendEvent(null, 'updateUnreadNotifications', { Nr: response.FinalResult });
                app.Phone.setNotifications(response.FinalResult);
                if (!response.FinalResult)
                    Elements.nonotif.show();
            }
        });
    };

    var calculateVisibleElements = function() {
        visibleElements = Math.ceil($(window).height() / Elements.notificationsList.find("div:first").outerHeight());
    };

    var addToList = function(data, addToStart) {
        if (!data || !data.length)
            return 0;

        if (!Templates.notificationsTemplateCompiled) {
            var source = Templates.notificationsTemplate.html();
            Templates.notificationsTemplateCompiled = Handlebars.compile(source);
        }

        var html = "";
        var startIndexInsert = 0;
        var last = notificari.length ? notificari[notificari.length - 1] : null;

        for (var i = 0; i < data.length; i++) {
            var n = data[i];
            n.POZA_SRC = Utils.getEmployeePhoto(n.ArePoza ? n.PRS_ID : 0, n.PRS_CNP);

            if (n.StartDate)
                n.StartDate = n.StartDate.parseDate();
            if (n.EndDate)
                n.EndDate = n.EndDate.parseDate();
            if (n.SENT_DATE)
                n.SENT_DATE = n.SENT_DATE.parseDate();

            if (n.Tip == 1) {
                if (n.IsHour) {
                    var text = Utils.getTimeDifferenceText(n.StartDate, n.EndDate);
                    n.Mesaj = translate('Notificari_Initiat_Ora_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), text, n.StartDate.format("hh:mm"), n.EndDate.format("hh:mm"));
                } else {
                    n.Mesaj = translate('Notificari_Initiat_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), Globalize.format(n.EndDate, "d"), Utils.getDateDiff(n.StartDate, n.EndDate), n.NrZileLucratoare);
                }

                n.DataText = translate('Notificari_Initiat_DataMesaj').format(Globalize.format(n.SENT_DATE, "d"));
                n.InitiatorText = translate('Notificari_Initiat_InitiatorText').format(n.Initiator);
                if (n.Descriere)
                    n.Mentiuni = translate('Notificari_Mentiuni').format(n.Descriere);
            } else if (n.Tip == 2) {
                if (n.STATUS == 1) {
                    if (n.IsHour) {
                        var text = Utils.getTimeDifferenceText(n.StartDate, n.EndDate);
                        n.Mesaj = translate('Notificari_Aprobat_Ora_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), text, n.StartDate.format("hh:mm"), n.EndDate.format("hh:mm"));
                    } else {
                        n.Mesaj = translate('Notificari_Aprobat_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), Globalize.format(n.EndDate, "d"), Utils.getDateDiff(n.StartDate, n.EndDate), n.NrZileLucratoare);
                    }
                    n.DataText = translate('Notificari_Aprobat_DataText').format(Globalize.format(n.SENT_DATE, "d"));
                    n.InitiatorText = translate('Notificari_Aprobat_InitiatorText').format(n.Initiator);
                } else {
                    if (n.IsHour) {
                        var text = Utils.getTimeDifferenceText(n.StartDate, n.EndDate);
                        n.Mesaj = translate('Notificari_Refuzat_Ora_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), text, n.StartDate.format("hh:mm"), n.EndDate.format("hh:mm"));
                    } else {
                        n.Mesaj = translate('Notificari_Refuzat_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), Globalize.format(n.EndDate, "d"), Utils.getDateDiff(n.StartDate, n.EndDate), n.NrZileLucratoare);
                    }
                    n.DataText = translate('Notificari_Refuzat_DataText').format(Globalize.format(n.SENT_DATE, "d"));
                    n.InitiatorText = translate('Notificari_Refuzat_InitiatorText').format(n.Initiator);
                    if (n.Motiv)
                        n.MotivText = translate('Notificari_Motiv').format(n.Motiv);
                }
            } else if (n.Tip == 3) {
                if (n.IsHour) {
                    var text = Utils.getTimeDifferenceText(n.StartDate, n.EndDate);
                    n.Mesaj = translate('Notificari_Modificat_Ora_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), text, n.StartDate.format("hh:mm"), n.EndDate.format("hh:mm"));
                } else {
                    n.Mesaj = translate('Notificari_Modificat_Mesaj').format(n.NumeConcediu, Globalize.format(n.StartDate, "d"), Globalize.format(n.EndDate, "d"), Utils.getDateDiff(n.StartDate, n.EndDate), n.NrZileLucratoare);
                }
                n.DataText = translate('Notificari_Modificat_DataText').format(Globalize.format(n.SENT_DATE, "d"));
                n.InitiatorText = translate('Notificari_Modificat_InitiatorText').format(n.Initiator);
                if (n.Descriere)
                    n.Mentiuni = translate('Notificari_Mentiuni').format(n.Descriere);
                if (n.Motiv)
                    n.MotivText = translate('Notificari_Motiv').format(n.Motiv);
            } else n.Mesaj = "";

            n.InlocuitorText = n.REPLACEMENT_NAME ? (translate('Notificari_Replacement') + ': ' + n.REPLACEMENT_NAME) : null;

            html += Templates.notificationsTemplateCompiled(n);

            if (!addToStart && last && last.CCD_ID == n.CCD_ID) {
                html = "";
                startIndexInsert = i + 1;
            }
        }

        if (startIndexInsert < data.length)
            for (var i = startIndexInsert; i < data.length; i++)
                notificari.push(data[i]);

        if (addToStart) {
            for (var i = data.length - 1; i >= 0; i--)
                notificari.unshift(data[i]);
            Elements.notificationsList.prepend(html);
        } else Elements.notificationsList.append(html);

        Elements.notificationsList.find('.new').each(function() {
            setEditable($(this), isEditing);
            $(this).removeClass('new');
        });

        addActionOnNotifications();

        return data.length - startIndexInsert;
    };

    var addActionOnNotifications = function() {
        Elements.notificationsList.find('.notification-container .notification-text').unbind().tap(function(e) {
            if (isEditing) {
                self.toggleEdit();
            } else {
                if (!app.Pages.Cerere.instance)
                    app.Pages.Cerere.instance = new CererePage(app.Pages.Cerere.container);

                var msg_id = $(this).parent().find('.delete-notification a').attr('data-tm-msg_id');
                if (msg_id) {
                    $(this).parents('.notification-container').remove();
                    readNotification(msg_id);
                }

                var ccd_id = $(this).parent().attr("data-tm-ccd_id");
                app.changePage(app.Pages.Cerere);
                app.Pages.Cerere.instance.setCerere(ccd_id);
            }

            return Event.stopEvent(e);
        });
    };

    self.initialize = override(self.initialize, function() {
        self.Title = translate('Module_Title_Notifications');
        app.translatePage(app.Pages.Notifications);

        pageContainer.find(".loadMore").show();

        $(document).bind(Events.Cerere_Added + ' ' + Events.Cerere_Modified + ' ' + Events.Cerere_Approved + ' ' + Events.Cerere_Refused + ' ' + Events.Cerere_Deleted, function() {
            self.getPullDownData();
        });

        pageContainer.bind('onBeforePageShow', function() {
            app.Phone.setBackbtnVisible(!app.HasPageChangedFromMenu);
            updateUnreadNotificationsCount();
        });

        $(document).bind('changedCompany', function() {
            self.refresh();
        });

        Elements.deleteAllNotifications.click(function() {
            app.MessagesFactory.showDialog(translate('Notificari_StergeTot_Title'), translate('Notificari_StergeTot_Confirmare'), [
                {
                    Text: translate('General_Da'),
                    Callback: function() {
                        app.TMMService.TMM.ReadAllNotifications(function() {
                            self.refresh();
                        });

                        app.MessagesFactory.hideDialog();
                        if (!isModified)
                            setHasModifiedView();
                    }
                },
                {
                    Text: translate('General_Nu'),
                    Callback: function() {
                        app.MessagesFactory.hideDialog();
                    }
                }
            ]);
        });
    });

    var readNotification = function(msg_id) {
        app.TMMService.TMM.ReadNotification(msg_id, function() {
            updateUnreadNotificationsCount();
        });
        $(this).parents('.notification-container').remove();
        if (!Elements.notificationsList.children().length) {
            pageContainer.find('.loadMore').hide();
            Elements.nonotif.show();
            if (app.CurrentPage.instance == self)
                app.Phone.setModuleAction(ModuleActions.None);

            if (isEditing)
                Elements.deleteAllNotifications.hide();
        } else if (visibleElements < Elements.notificationsList.children().length)
            self.getPullUpData();
    };

    this.setModuleAction = override(self.setModuleAction, function() {
        if (app.Phone) {
            if (notificari.length)
                app.Phone.setModuleAction(ModuleActions.Edit);
            else app.Phone.setModuleAction(ModuleActions.None);
        }
    });

    this.goBack = function() {
        if (isEditing)
            return self.toggleEdit();

        if (self.LastPageHash)
            app.changePage(app.getPageByHash(self.LastPageHash), true);
        else app.changePage(app.Pages.Dashboard, true);
    };

    self.initialize();
};
extend(NotificationsPage, TMMobilePage);